﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Pow {
	class Enemy : DrawableGameComponent {
		Game1 game;
		Texture2D texture;
		Vector2 textureDimensions;
		public Rectangle enemyBounder;
		//public int inimigosNaTela = 15;
		public Vector2 myPosition;
        Vector2 movimento = new Vector2(2,0);
        Vector2 direcao = new Vector2(1,1);
		//int movimento = 2;
        //int direcao = 1;
		int frame = 2;
		public bool active = false;
		public bool letra_alvo = false;
        public bool atirando = false;
        public bool vitima = true;
        public KeyboardState oldtecla;
        public KeyboardState tecla;
		SpriteFont font;
		Vector2 positionTecla = new Vector2(390, 280);
		String currentString;
		public Keys currentKey;
        public Keys teclaCerta;
		Keys[] keysCollection = new Keys[6] { Keys.Q, Keys.W, Keys.E, Keys.R, Keys.T, Keys.Y };
		Vector2[] spawnPoints;
        public bool target = false;
        public bool oldtarget = false;
        Jogador jogador;
        long oldSecond = 0;

        int randomVitima;

		public Enemy(Game1 game, Jogador jogador)
			: base(game) {
			this.game = game;

			texture = game.Content.Load<Texture2D>("Naves-1");
			textureDimensions = new Vector2(texture.Width, texture.Height);
			currentString = " ";
			font = game.Content.Load<SpriteFont>("SpriteFont2");

            this.jogador = jogador;

			//Vector2 spawnPoint = new Vector2(0, (game.graphics.PreferredBackBufferHeight / 2) - textureDimensions.Y / 2);
			Vector2 screenSize = new Vector2(game.graphics.PreferredBackBufferWidth, game.graphics.PreferredBackBufferHeight);
			spawnPoints = new Vector2[4] { new Vector2(0, 450), new Vector2(0, 100), new Vector2(screenSize.X - 100, 450), new Vector2(screenSize.X - 100, 100) };
			//Vector2 spawnPoint = spawnPoints[new Random().Next(0,spawnPoints.Length)];
			//myPosition = spawnPoint;

            
		}

		public void Spawn() {
            int spawnPointsIndex = new Random().Next(0, spawnPoints.Length); 
			Vector2 spawnPoint = spawnPoints[spawnPointsIndex];
			myPosition = spawnPoint;
			active = true;
            direcao.X = spawnPoint.X == 0 ? 1 : -1;
            direcao.Y = spawnPoint.X == 0 ? 1 : -1;
            randomVitima = new Random().Next(3);
            vitima = randomVitima!=0 ? true : false;
            //vitima = true;
            //vitima = (randomVitima.Next(100) % 2 ==0) ? true : false;

            Console.WriteLine(randomVitima + " spawning new enemy" + active + " (" + myPosition.X + "," + myPosition.Y + ")");
		}


		/*
		 * spawnPoints possiveis sao 4, 2 pontos na direita, 2 pontos na esquerda
		 * o objeto se move rumo ao limite oposto da tela e pode tomar decisao em 3 pontos.
		 * _________________
		 * |   |   |   |   |
		 * |   o   o   o   |
		 * |   |   x   |   |
		 * |   o   o   o   |
		 * |___|___|___|___|
		 * 
		 * 
		 */
		/* protected override void LoadContent()
		 {
            
		 }
		 */

		public override void Update(GameTime gameTime) {
			if (!active) {
				myPosition = new Vector2(-100, -100);
				enemyBounder = new Rectangle();
                movimento.Y = 0;
                movimento.X = 2;
                target = false;
                oldtarget = false;
                vitima = false;
			}
			else {
                if (myPosition.X == 200 && myPosition.Y == 100 && direcao.X == 1 && vitima)
                {
                    movimento.Y = 2;
                    //movimento.X *= 2;
                }
                if (myPosition.X == 530 && myPosition.Y == 100 && direcao.X == -1 && vitima)
                {
                    movimento.Y = -2;
                    //movimento.X *= 2;
                }
                if (myPosition.X == 190 && myPosition.Y == 450 && direcao.X == 1 && vitima)
                {
                    movimento.Y = -2;
                    //movimento.X *= 2;
                }
                if (myPosition.X == 540 && myPosition.Y == 450 && direcao.X == -1 && vitima)
                {
                    movimento.Y = 2;
                    //movimento.X *= 2;
                }
				myPosition = new Vector2(myPosition.X + (movimento.X*direcao.X), myPosition.Y + (movimento.Y*direcao.Y));
				enemyBounder = new Rectangle((int) myPosition.X, (int) myPosition.Y, (int) textureDimensions.X / 8, (int) textureDimensions.Y / 2);

				// Acima em (int)textureDimensions.X, dividi o valor por 4 para que o bounder do inimigo ficasse do tamanho da nave
				// Em texture.Width dividi por 8 para que a nave fosse até o final da tela
				if (myPosition.X > game.graphics.PreferredBackBufferWidth || myPosition.X < 0) {
					active=false;
				}
				

				// Animação da nave

                if (oldSecond == 0) oldSecond = gameTime.TotalGameTime.Ticks;
                //Console.WriteLine(gameTime.TotalGameTime.Ticks);
                if (gameTime.TotalGameTime.Ticks - oldSecond > 1000000)
                {
                    frame = (frame == 2)?3:2;
                    oldSecond = gameTime.TotalGameTime.Ticks;
                }
                //counter++;
                //frame = (counter / 10) + 2;
                //if (counter >= 19)
                //    counter = 0;

			}

            tiro();
            removerInimigo();
            colisao();
            if (!letra_alvo)
            {
                currentKey = keysCollection[new Random().Next(0, keysCollection.Length)];
                currentString = currentKey.ToString();
            }
            else
            {
                teclaCerta = currentKey;
            }
			base.Update(gameTime);
		}

		public override void Draw(GameTime gameTime) {

			//if (!active) return;

			game.spriteBatch.Draw(texture, myPosition, new Rectangle(140 * frame, 0, 140, 140), Color.White, 0f, Vector2.Zero, .5f, SpriteEffects.None, 0);
			//if (letra_alvo)
				game.spriteBatch.DrawString(font, currentString, new Vector2(myPosition.X + 20, myPosition.Y - 20), Color.White);
            //else
            //    currentKey = keysCollection[new Random().Next(0, keysCollection.Length)];
            //currentString = currentKey.ToString();
            //game.spriteBatch.DrawString(font, currentString, new Vector2(myPosition.X + 20, myPosition.Y - 20), Color.White);

		}

        private void tiro()
        {
            
            atirando = false;

            tecla = Keyboard.GetState();
            //Console.WriteLine("currentKey:"+currentKey);

            if (tecla.IsKeyDown(teclaCerta) && !oldtecla.IsKeyDown(teclaCerta) && !jogador.gameover)
            {
                Console.WriteLine("TIRO!!");
                //Som do Tiro
                jogador.tiroFX.Play();
                atirando = true;
                //jogador.score++;
                //jogador.miraCor = Color.Yellow;
            }
            //if (tecla. != teclaCerta)
            //{
            //    jogador.score -= 10;
            //}

            oldtecla = tecla;
        }

        private void colisao()
        {
            if (jogador.miraBounder.Intersects(enemyBounder))
            {
                target = true;
                letra_alvo = true;
                jogador.miraCor = Color.Green;
                if (!oldtarget)
                    oldtarget = true;
            }
            else
            {
                target = false;
                letra_alvo = false;
                if (active && oldtarget && !target)
                {
                    jogador.life--;
                    jogador.evilFX.Play();
                    oldtarget = false;
                    jogador.miraCor = Color.Aqua;
                }
            }

        }

        private void removerInimigo()
        {
            
            if (atirando && target)
            {
                active = false;
                //Executa a explosão e tira o inimigo da tela
                //Som da explosao
                //jogador.life++;
                jogador.tiroFX.Play();
                jogador.explosaoFX.Play();
                Console.WriteLine("MORREU:");
                jogador.score += 10;
                jogador.miraCor = Color.Red;

            }
        }




	}
}
